package Solution.problem095.UniqueBinarySearchTreesII;

import common.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @program Leetcode
 * @description:
 * @author: lishangsheng
 * @create: 2019/07/08 14:43
 */
public class Solution {
    public List<TreeNode> generateTrees(int n) {
        List<TreeNode> res=new ArrayList<>();
        if(n<1){
            return res;
        }

        return generate(1,n);
    }

    private List<TreeNode> generate(int start,int end){
        List<TreeNode> result=new ArrayList<>();
        /*生成的终止条件*/
        if(start>end){
            result.add(null);
            return result;
        }

        for(int i=start;i<=end;i++){
            /*生成左子树*/
            List<TreeNode> leftNodes=generate(start,i-1);
            /*生成右子树*/
            List<TreeNode> rightNodes=generate(i+1,end);
            /*左右子树取子树，生成一个BST*/
            for(TreeNode left:leftNodes){
                for(TreeNode right:rightNodes){
                    TreeNode root=new TreeNode(i);
                    root.left=left;
                    root.right=right;
                    result.add(root);
                }
            }

        }
        return result;
    }


    public int numTrees(int n) {
        if (n <= 0)
            return 0;
        int[] res = new int[n + 1];
        res[0] = 1;
        res[1] = 1;
        for (int i = 2; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                res[i] += res[j - 1] * res[i - j];
            }
        }

        return res[n];
    }
}
